package com.wnhz.work.yz.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.alipay.PayResult;
import com.wnhz.work.yz.bean.ALiBean;
import com.wnhz.work.yz.bean.WeiXinPayBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * ----(订单)支付
 */
public class ChoosePayActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_pay_money;
    private TextView tv_pay_type2;
    private TextView tv_no_enough;

    private String order_no;
    private String money;
    private RelativeLayout rl_pay_type1;

    private RelativeLayout rl_pay_type3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_pay);

        initData();
        initTitle();
        initView();
    }

    private void initData() {
        order_no = getIntent().getStringExtra("order_no");
        money = getIntent().getStringExtra("money");
    }


    private TextView title;

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("支付");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
    }


    private void initView() {
        tv_pay_money = (TextView) findViewById(R.id.tv_pay_money);
        tv_pay_type2 = (TextView) findViewById(R.id.tv_pay_type2);
        tv_no_enough = (TextView) findViewById(R.id.tv_no_enough);

        rl_pay_type1 = (RelativeLayout) findViewById(R.id.rl_pay_type1);
        rl_pay_type1.setOnClickListener(this);
        rl_pay_type3 = (RelativeLayout) findViewById(R.id.rl_pay_type3);
        rl_pay_type3.setOnClickListener(this);

        findViewById(R.id.rl_pay_type2).setOnClickListener(this);
        showDialog();
        upload();
    }

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", order_no);
        XUtil.Post(Url.ORDER_TOPAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //   Log.i(TAG, "onSuccess:order_no=== " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    JSONObject jsonObject2 = jsonObject.optJSONObject("info");
                    String wallet = jsonObject2.optString("wallet");
                    String total_fee = jsonObject2.optString("total_fee");
                    String order_no = jsonObject2.optString("order_no");

                    tv_pay_money.setText("¥ " + total_fee);
                    tv_no_enough.setText("(" + wallet + ")");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void uploadPay2() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", order_no);
        XUtil.Post(Url.PAY_WALLETPAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                // Log.i(TAG, "onSuccess: order_no= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        // MyToast(info);
                        JSONObject infos = new JSONObject(info);
                        Intent intent = new Intent(ChoosePayActivity.this, PaySuccessActivity.class);
                        //   Log.e("----",infos.optString("order_no"));
                        intent.putExtra("str_number", infos.optString("order_no"));
                        intent.putExtra("str_tiem", infos.optString("time"));
                        intent.putExtra("str_price", infos.optString("total_fee"));
                        startActivity(intent);
                        finish();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("---", "cw");
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_main_left:
                finish();
                break;

            //余额
            case R.id.rl_pay_type2:
                showDialogv7("确定用余额支付吗？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        uploadPay2();
                    }
                });

                break;
            //支付宝
            case R.id.rl_pay_type1:
                aliPay();
                break;
            //微信支付
            case R.id.rl_pay_type3:
                weixinPay();
                break;
            default:
                break;
        }

    }

    private void weixinPay() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", order_no);
        XUtil.Post(Url.PAY_WXPAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("==微信支付===", result);
                Gson gson = new Gson();
                WeiXinPayBean weiXinPayBean = gson.fromJson(result, WeiXinPayBean.class);
                final IWXAPI msgApi = WXAPIFactory.createWXAPI(ChoosePayActivity.this, null);
                msgApi.registerApp(MyApplication.getInstance().WXAPP_ID);
                PayReq req = new PayReq();

                req.appId = weiXinPayBean.getAppid();
                req.partnerId = weiXinPayBean.getPartnerid();
                req.prepayId = weiXinPayBean.getPrepayid();
                req.nonceStr = weiXinPayBean.getNoncestr();
                req.timeStamp = weiXinPayBean.getTimestamp() + "";
                req.packageValue = "Sign=WXPay";

                req.sign = weiXinPayBean.getSign();
                MyApplication.getInstance().api.sendReq(req);
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private String TAG = "ChoosePayActivity";

    private void aliPay() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", order_no);
        XUtil.Post(Url.PAY_ALIPAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: order_no= " + result);
                Gson gson = new Gson();
                ALiBean bean = gson.fromJson(result, ALiBean.class);
                if ("1".equals(bean.getResult())) {
                    Message msg = Message.obtain();
                    msg.what = TOALIPAY;
                    msg.obj = bean.getInfo();
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }


    /**
     * ------------------------------支付宝支付------------------------------------------------
     */

    private static final int SDK_PAY_FLAG = 1;
    private static final int TOALIPAY = 3;

    public void payV2(ALiBean.InfoEntity info) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        final String orderinfo = "_input_charset=\"" + info.get_input_charset() + "\"&body=\"" + info.getBody() + "\"&notify_url=\"" + info.getNotify_url() + "\"&out_trade_no=\"" + info.getOut_trade_no() + "\"&partner=\"" + info.getPartner() + "\"&payment_type=\"" + info.getPayment_type() + "\"&seller_id=\"" + info.getSeller_id() + "\"&service=\"" + info.getService() + "\"&subject=\"" + info.getSubject() + "\"&total_fee=\"" + info.getTotal_fee() + "\"&sign=\"" + info.getSign() + "\"&sign_type=\"" + info.getSign_type() + "\"";

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ChoosePayActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //   Log.e("-----", resultInfo + "---" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ChoosePayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ChoosePayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                case TOALIPAY: {
                    ALiBean.InfoEntity obj = (ALiBean.InfoEntity) msg.obj;
                    payV2(obj);
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

}
